// src/utils/auth.js
import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'
const RefreshTokenKey = 'Admin-Refresh-Token'

// 获取访问令牌
export function getToken() {
    return Cookies.get(TokenKey)
}

// 获取刷新令牌
export function getRefreshToken() {
    return Cookies.get(RefreshTokenKey)
}

// 设置访问令牌
export function setToken(token, expires = 24 * 60 * 60) {
    Cookies.set(TokenKey, token, {
        expires: expires / (24 * 60 * 60), // 默认1天过期
        secure: process.env.NODE_ENV === 'production', // 生产环境启用secure
        sameSite: 'strict' // 防止CSRF攻击
    })
}

// 设置刷新令牌
export function setRefreshToken(token, expires = 7 * 24 * 60 * 60) {
    Cookies.set(RefreshTokenKey, token, {
        expires: expires / (24 * 60 * 60), // 默认7天过期
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'strict'
    })
}

// 移除所有令牌
export function removeToken() {
    Cookies.remove(TokenKey)
    Cookies.remove(RefreshTokenKey)
}

// 检查是否已认证
export function isAuthenticated() {
    return !!getToken()
}

// 从响应头中提取并存储令牌
export function extractAndStoreTokens(response) {
    const token = response.headers['authorization'] || response.data?.token
    const refreshToken = response.headers['x-refresh-token'] || response.data?.refreshToken

    if (token) {
        setToken(token.replace('Bearer ', ''))
    }
    if (refreshToken) {
        setRefreshToken(refreshToken)
    }
}